package com.shiroha.notification.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.shiroha.common.event.ServiceEvent;
import com.shiroha.common.event.ServiceEventPublisher;
import com.shiroha.common.event.ServiceEventType;
import com.shiroha.common.exception.InternalServiceException;
import com.shiroha.notification.mapper.NotificationMapper;
import com.shiroha.notification.pojo.Notification;
import com.shiroha.notification.service.INotificationService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;

@Service
@AllArgsConstructor
@Slf4j
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification> implements INotificationService {

    private final ServiceEventPublisher publisher;

    /**
     * 发布通知
     *
     * @param serviceEventType 通知类型
     * @param payload          消息负载
     * @return 发布通知是否成功
     */
    @Override
    public boolean publishNotification(ServiceEventType serviceEventType, Map<String, Object> payload) {
        try {
            // 发布事件
            ServiceEvent event = ServiceEvent.create(this, serviceEventType, payload);
            publisher.publishEvent(event);

            // 保存到数据库
            Notification notification = new Notification();
            UUID userId = UUID.fromString((String) payload.get("userId"));
            notification.setUserId(userId);
            notification.setType(serviceEventType);
            notification.setPayload(payload);
            return true;
        }catch (Exception e) {
            log.error("事件创建失败");
            throw new InternalServiceException("创建事件失败");
        }
    }
}
